package com.ja.util;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.ja.controller.ChatWebSocketHandler;
import com.ja.domain.User;
/**
 * 前台用户websocket 拦截器
 * @author Administrator
 *
 */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor{

	@Override
	public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1, WebSocketHandler arg2, Exception arg3) {
		
	}

	@Override
	public boolean beforeHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1, WebSocketHandler arg2,
			Map<String, Object> arg3) throws Exception {
		//获取httpsession
		if(arg0 instanceof ServletServerHttpRequest) {
			 ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) arg0;
			 HttpSession httpSession = servletRequest.getServletRequest().getSession(false);
			 if (httpSession != null) {  
				 User user = (User)httpSession.getAttribute("user");
				 if(ChatWebSocketHandler.sessions.size() >= 1) {
					 for(WebSocketSession w : ChatWebSocketHandler.sessions) {
						 if(w.getAttributes().get("name").equals(user.getName())) {
							 return false;
						 }else {
							 arg3.put("name",user.getName()); 
						 }
					 }
				 }else {
					 arg3.put("name",user.getName());
				 }
	            }else{
	                return false;
	            }  
		}
		return true;
	}


}
